<template>
  <div class="admin-course-types">
    <!-- 侧边栏 -->
    <admin-sidebar ref="sidebarRef" :class="{ collapsed: sidebarCollapsed }"/>

    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
      <!-- 顶部导航 -->
      <admin-header
          page-title="课程类型管理"
          :sidebar-collapsed="sidebarCollapsed"
          @toggle-sidebar="toggleSidebar"
      />

      <!-- 内容区域 -->
      <div class="content">
        <el-card shadow="hover">
          <div class="card-header-actions">
            <el-button type="primary" @click="showAddDialog">
              <el-icon>
                <Plus/>
              </el-icon>
              新增课程类型
            </el-button>
          </div>

          <el-table
              :data="courseTypes"
              style="width: 100%"
              border
              stripe
          >
            <el-table-column prop="id" label="类型ID"></el-table-column>
            <el-table-column prop="name" label="类型名称"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <div class="status-container">
                  <el-tag :type="scope.row.status === '1' || scope.row.status === 1 ? 'success' : 'danger'"
                          class="status-tag">
                    {{ scope.row.status === '1' || scope.row.status === 1 ? '上架' : '下架' }}
                  </el-tag>
                  <el-switch
                      :model-value="scope.row.status === '1' || scope.row.status === 1"
                      @change="toggleStatus(scope.row)"
                      class="status-switch"
                  />
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="createTime" label="创建时间">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
              <template #default="scope">
                <el-button type="primary" text @click="editType(scope.row)">编辑</el-button>
                <el-button type="danger" text @click="deleteType(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <!-- 新增/编辑类型对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="400px"
        @close="resetForm"
    >
      <el-form :model="typeForm" :rules="rules" ref="typeFormRef" label-width="80px">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="typeForm.typeName" placeholder="请输入类型名称"
                    @blur="checkName(typeForm.typeName)"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {Plus} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'
import {addCourseTypes, checkNameUnique,queryAll,updateCourseTypesName,updateCourseTypesStatus} from "@/api/CourseTypes.js";

const router = useRouter()
const route = useRoute()

// 侧边栏相关
const sidebarCollapsed = ref(false)
const sidebarRef = ref(null)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增课程类型')
const currentTypeId = ref(null)
const typeFormRef = ref(null)

// 表单数据
const typeForm = reactive({
  typeName: ''
})

const rules = {
  typeName: [
    {required: true, message: '请输入类型名称', trigger: 'blur'},
    {min: 1, max: 50, message: '类型名称长度在 1 到 50 个字符', trigger: 'blur'}
  ]
}

// 获取管理员信息
const adminInfo = computed(() => {
  const info = localStorage.getItem('adminInfo')
  if (info) {
    return JSON.parse(info)
  }
  // 为了开发测试，提供一个完整的默认管理员信息
  return {
    name: '管理员',
    username: 'admin', // 添加username属性，避免登录检查失败
    isSuperAdmin: true
  }
})
//检测课程名称的唯一性
const checkName = (name) => {
  checkNameUnique({"name": name}).then(res => {
    console.log(res)
    if (res.data) {
      //可用
      ElMessage.success("课程类型可用")
      return true
    } else {
      ElMessage.error("课程类型重复")
      return false
    }
  })
}
// 模拟课程类型数据
const courseTypes = ref([])
//状态切换
const toggleStatus = (courseTypes) => {
  // 获取当前状态
  const currentStatus = courseTypes.status
  // 切换状态值
  const newStatus = (currentStatus === '1' || currentStatus === 1) ? '0' : '1'
  // 更新用户状态
  courseTypes.status = newStatus
  // 模拟API调用更新状态
  updateCourseTypesStatus({"id":courseTypes.id,"status":courseTypes.status}).then(res=>{
    if(res.code===200){
      ElMessage.success(`${newStatus === '1' ? '启用' : '禁用'}成功`)
    }else{
      ElMessage.error(`${newStatus === '1' ? '启用' : '禁用'}失败`)
    }
  })
}
// 计算当前激活的菜单
const activeMenu = ref('')

// 处理菜单选择
const handleMenuSelect = (key, keyPath) => {
  activeMenu.value = key
}

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('adminToken')
  localStorage.removeItem('adminInfo')
  ElMessage.success('退出成功')
  router.push('/admin/login')
}

// 处理个人信息
const handleProfile = () => {
  ElMessage.info('个人信息功能开发中')
}

// 格式化日期
const formatDate = (dateStr) => {
  return dateStr ? new Date(dateStr).toLocaleString('zh-CN') : ''
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增课程类型'
  currentTypeId.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑类型
const editType = (type) => {
  dialogTitle.value = '编辑课程类型'
  currentTypeId.value = type.id
  typeForm.typeName = type.name
  dialogVisible.value = true
}

// 删除类型
const deleteType = (type) => {
    ElMessage.warning('该类型关联课程，不可删除')
    return
  ElMessageBox.confirm(
      `确定要删除类型「${type.name}」吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(() => {
        // 模拟删除操作
        const index = courseTypes.value.findIndex(item => item.id === type.id)
        if (index !== -1) {
          courseTypes.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      })
      .catch(() => {
        // 取消删除
      })
}

// 重置表单
const resetForm = () => {
  if (typeFormRef.value) {
    typeFormRef.value.resetFields()
  }
  typeForm.typeName = ''
  currentTypeId.value = null
}

// 提交表单
const submitForm = () => {
  try {
    checkNameUnique({"name": typeForm.typeName}).then(res => {
      if (res.data) {
        typeFormRef.value.validate()
        if (currentTypeId.value) {
          // 编辑操作
         updateCourseTypesName({id: currentTypeId.value,name: typeForm.typeName}).then(res=>{
           if (res.code === 200) {
             queryAllCourseTypes()
             ElMessage.success('编辑成功')
           }
         })
        } else {
          // 新增操作
          addCourseTypes({name: typeForm.typeName}).then(res => {
            if (res.code === 200) {
              queryAllCourseTypes()
              ElMessage.success('新增成功')
            }
          })

        }
        dialogVisible.value = false
        resetForm()
      }
    })

  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
//查询全部课程类别信息
const queryAllCourseTypes=()=>{
  queryAll().then(res=>{
    courseTypes.value = res.data
  })
}
// 检查登录状态
const checkLoginStatus = () => {
  const adminToken = localStorage.getItem('adminToken')
  if (!adminToken || !adminInfo.username) {
    ElMessage.error('请先登录')
    router.push('/admin/login')
  }
}

onMounted(() => {
  // 注释掉登录验证，方便开发测试
  // checkLoginStatus()
  queryAllCourseTypes()
})
</script>

<style scoped>
.admin-course-types {
  display: flex;
  min-height: 100vh;
  background-color: #f0f2f5;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  margin-left: 250px;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  transition: margin-left 0.3s;
}

.main-content.sidebar-collapsed {
  margin-left: 64px;
}

/* 内容区域样式 */
.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.card-header-actions {
  margin-bottom: 20px;
}
</style>